const puppeteer = require('puppeteer');

(async () => {

    var express = require('express');
    var app = express();
    var cookieParser = require('cookie-parser')
    var bodyParser = require('body-parser');

    //静态资源
    app.use('/static', express.static('website'));
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(cookieParser())

    var errMsg = {
        0: '成功',
        10001: '【enc】失效,请从淘宝登录并从cookie复制并更新！',
        10002: '【x5sec】失效,请从淘宝登录并从s.taobao.com网页的cookie复制并更新node服务！'
    }
    app.get('/', (req, res) => {
        res.send('主页')
    })

    const browser = await puppeteer.launch({
        args: [
            '--disable-web-security'
        ],
        headless: true,
        ignoreHTTPSErrors: true,
        defaultViewport: null,
        timeout: 10000,
        devtools: false,
        slowMo: 250,
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
    });

    // 输出 JSON 格式
    app.post('/getTaobaoGoods(.json)', async (req, res) => {
        res.header('Access-Control-Allow-Origin', '*');
        //收集参数
        var url = req.body.url

        var result = {code: 0};
        const page = await browser.newPage();
        try {
            page.setDefaultTimeout(30000)

            //设置cookie信息
            let x5secObj = {
                url: 'https://s.taobao.com',
                name: 'x5sec',
                value: req.body.tb_x5sec || '',
            };
            let encObj = {
                url: 'https://www.taobao.com',
                name: "enc",   //目前过期时间为2029年，如果需要刷新则登录淘宝从cookie中获取
                value: req.body.tb_enc || 'BVazFNbLWj2xGrimjsV8KMjZtTU42AjhiNChoIXoJvnwMSAvqKoWwJkG7iA0ZXqUrT%2Bpvekac5Alymq75tXFcQ%3D%3D',
                domain: '.taobao.com',
            }
            await page.setCookie(x5secObj, encObj, Object.assign(encObj, {url: 'https://s.taobao.com',}));

            //跳转页面
            await page.goto(url);

            /** 验证页面 */
            if (page.url().includes('login.taobao.com')) {
                //页面进入了登录页
                result.code = 10001
            } else if (await page.$('#x5secdata') != null) {
                //页面进入了滑动验证页面
                result.code = 10002
            } else {  //成功,收集商品数据
                result.data = [];
                let $items = await page.$$('.m-itemlist .items .item');
                for (let $item of $items) {
                    result.data.push({
                        price: $item.getElementsByClassName('price')[0].innerText,
                        name: $item.getElementsByClassName('title')[0].innerText,
                        shopname: $item.getElementsByClassName('shop')[0].innerText,
                        detailUrl: $item.getElementsByClassName('title')[0].getElementsByClassName('J_ClickStat')[0].getAttribute('href')
                    })
                }
            }

        } catch (e) {
            console.error(e)
        } finally {
            console.log('訪問地址:' + page.url())
            res.send(Object.assign(result, {
                message: errMsg[result.code],
                url: page.url(),
                html: await page.content()
            }))

            page.close()
        }
    })


    var server = app.listen(18081, function () {

        var host = server.address().address
        var port = server.address().port

        console.log("node服务器，访问地址为 http://%s:%s", host === "::" ? 'localhost' : host, port)

    })

})();

